package cn.edu.scau.cmi.yanghongyu.restcontroller;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.ema.controller.base.CmiController;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Brand;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Expire;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.ema.domain.Producer;
import cn.edu.scau.cmi.ema.domain.Productcode;
import cn.edu.scau.cmi.ema.domain.Site;
import cn.edu.scau.cmi.ema.domain.Storemethod;
import cn.edu.scau.cmi.ema.domain.Subject;
import cn.edu.scau.cmi.ema.domain.Taste;
import cn.edu.scau.cmi.ema.domain.Unit;
import cn.edu.scau.cmi.ema.domain.Url;
import cn.edu.scau.cmi.ema.domain.User;
import cn.edu.scau.cmi.ema.service.FoodtypeService;
import cn.edu.scau.cmi.yanghongyu.dao.FrontSpiderDAO;
import cn.edu.scau.cmi.yanghongyu.dao.FrontEchartDAO;

@Controller
public class FrontSpiderEventController extends CmiEmaController {

	@Autowired
	FrontEchartDAO frontEchartDAO;
	
	@Autowired
	FrontSpiderDAO frontCrawlerDAO;

	private String[] addressLevel = new String[] {"region", "country", "province", "city", "area", "street"};
	
//	标记爬取的事件是否是EMA事件，并完善数据和数据集。
	@RequestMapping("/frontMarkCrawlerEvent")
	public ModelAndView frontMarkCrawlerEvent(@RequestParam Map<String, String> tfMap) {
		ModelAndView mav = new ModelAndView();
		try {
			Long id = Long.valueOf(tfMap.get("id"));
			Integer isEma = Integer.valueOf(tfMap.get("isEma"));

			if (id != -1) {

				if (isEma == 1) {
					
					Storemethod storemethod = storemethodService.findStoremethodByPrimaryKey(-2);
					Expire expire = expireService.findExpireByPrimaryKey(-2);
					Productcode productcode = productcodeService.findProductcodeByPrimaryKey(-2);
					Taste taste = tasteService.findTasteByPrimaryKey(-2);
					Site site = siteService.findSiteByPrimaryKey(-2);
					Unit unit = unitService.findUnitByPrimaryKey(-2);
					User user = userService.findUserByPrimaryKey(-2);
					Address address = addressService.findAddressByPrimaryKey(-2);
					
					// 保存ema事件
					Map<String, String> map = frontCrawlerDAO.getCrawlerEventById(id);
					String eventDescription = map.get("mainContent");
					
					String eventName = tfMap.get("eventName");
					String subjectName = tfMap.get("subjectName");
					String url = tfMap.get("url");
					String foodbatchName = tfMap.get("foodbatchName");
					String foodName = tfMap.get("foodName");
					Integer foodtypeId = Integer.valueOf(tfMap.get("foodtypeId"));
					String brandName = tfMap.get("brandName");
					String producerName = tfMap.get("producerName");
					Integer producerAddressId = -2;
					

					Foodtype foodtype = foodtypeService.findFoodtypeByPrimaryKey(foodtypeId);
					if (foodtype == null)
						throw new NullPointerException("未找到foodtype");
					
					// 使用默认producer或保存新的producer
					Producer producer = producerService.findProducerByPrimaryKey(-2);
					if (producerName != null) {
						Set<Producer> set = producerDAO.findProducerByName(producerName);
						if (!set.isEmpty()) {
							producer = set.iterator().next();
						} else {
							for (String addr : addressLevel) {
								Integer addrTmp = Integer.valueOf(tfMap.get(addr));
								if (addrTmp != -1) producerAddressId = addrTmp;
							}
							
							producer = new Producer();
							producer.setAddress(addressService.findAddressByPrimaryKey(producerAddressId));
							producer.setName(producerName);
							producer = producerService.saveProducer(producer);
						}
						
					}
					
					// 使用默认brand或保存新的brand
					Brand brand = brandService.findBrandByPrimaryKey(-2);
					if (brandName != null) {
						Set<Brand> set = brandDAO.findBrandByName(brandName);
						if (!set.isEmpty()) {
							brand = set.iterator().next();
						} else {
							brand = new Brand();
							brand.setName(brandName);
							brand = brandService.saveBrand(brand);
						}
					}
					
					// 使用已有food或保存新的food
					Food food = null;
					if (foodName != null) {
						Set<Food> set = foodDAO.findFoodByName(foodName);
						if (!set.isEmpty()) {
							food = set.iterator().next();
						} else {
							food = new Food();
							food.setName(foodName);
							food.setFoodtype(foodtype);
							food.setBrand(brand);
							food.setProducer(producer);
							food.setStoremethod(storemethod);
							food.setExpire(expire);
							food.setProductcode(productcode);
							food.setTaste(taste);
							food = foodService.saveFood(food);
						}
					}
					
					// 使用已有的foodbatch或保存新的foodbatch
					Foodbatch foodbatch = null;
					String batchName = foodbatchName;
					if (foodbatchName == null) {
						foodbatchName = "虚拟食物批次" + food.getId();
						batchName = "该事件没有涉及的食物批次信息";
					}
					{
						Set<Foodbatch> set = foodbatchDAO.findFoodbatchByName(foodbatchName);
						if (!set.isEmpty()) {
							foodbatch = set.iterator().next();
						} else {
							foodbatch = new Foodbatch();
							foodbatch.setName(foodbatchName);
							foodbatch.setBatch(batchName);
							foodbatch.setDate(Calendar.getInstance());
							foodbatch.setUnit(unit);
							foodbatch.setFood(food);
							foodbatch = foodbatchService.saveFoodbatch(foodbatch);
						}
					}
					
					// 使用已有的subject或保存新的subject
					Subject subject = null;
					if (subjectName != null) {
						Set<Subject> set = subjectDAO.findSubjectByName(subjectName);
						if (!set.isEmpty()) {
							subject = set.iterator().next();
						} else {
							subject = new Subject();
							subject.setName(subjectName);
							subject = subjectService.saveSubject(subject);
						}
					}
					
					// 使用已有的uri或保存新的uri
					Url uri = null;
					if (url != null) {
						Set<Url> set = urlDAO.findUrlByValue(url);
						if (!set.isEmpty()) {
							uri = set.iterator().next();
						} else {
							uri = new Url();
							uri.setName(url);
							uri.setValue(url);
							uri.setSite(site);
							uri = urlService.saveUrl(uri);
						}
					}
					
					// 保存event
					Event event = new Event();
					event.setName(eventName);
					event.setDescription(eventDescription);
					event.setParent(eventService.findEventByPrimaryKey(-2));
					event.setSubject(subject);
					event.setFoodbatch(foodbatch);
					event.setUrl(uri);
					event.setAuditor(user);
					event.setSourceAddress(address);
					event.setDiscoveryAddress(address);
					event.setReportor(user);
					event.setStatus(false);
					event = eventService.saveEvent(event);
				}

				// 保存标记
				if (!frontCrawlerDAO.markCrawlerEvent(id, isEma))
					throw new SQLException("更新标记失败");
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
//			System.out.println(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
//			System.out.println(e.getMessage());
		}

		Map<String, String> map = frontCrawlerDAO.getSingleMarklessCrawlerEvent();

		String mainContent = map.get("mainContent");
		if (mainContent != null) {
			mainContent = mainContent.replaceAll("\\r\\n", "</p><p>");
			mainContent = mainContent.replaceAll("\\n", "</p><p>");
			mainContent = "<p>" + mainContent;
			mainContent = mainContent + "</p>";
			map.put("mainContent", mainContent);
		}

		mav.addObject("tf", map);
		mav.setViewName("front/frontMarkCrawlerEvent.jsp");

		return mav;
	}

//	TODO 2021-0515 这个功能好像没有被使用
	@RequestMapping("/frontAuditCrawlerEvent/{id}/{isEma}")
	public ModelAndView frontAuditCrawlerEvent(@PathVariable Long id, @PathVariable Integer isEma) {
		ModelAndView mav = new ModelAndView();

		Map<String, String> tfMap = frontCrawlerDAO.getCrawlerEventById(id);
		tfMap.put("isEma", isEma.toString());

		mav.addObject("tf", tfMap);
		mav.setViewName("front/tfaudit.jsp");

		return mav;
	}

}
